// pages/caseDescribe/caseDescribe.js
import request from '../../utils/config.js';
import util from '../../utils/util.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // isFile: false,
    windowHeight: wx.getSystemInfoSync().windowHeight - 91,
    caseInfoData: "",
    trackRecords: [],
    trackRecordsAll:[],
    showMoreBtn:false,
    showMoreTrick:false,
    lastLength: 0,
    firstLength: 0,
    isToastBg: false,
    isToast: false,
    faceListDefault: [
      {
        img: 'face1.png', imgSlt: 'face1_slt.png', text: '吐槽', style: '#747474', style_slt: '#487da5', laberList: [
          { name: "服务态度差", slt: false },
          { name: "工作效率低", slt: false },
          { name: "不专业", slt: false },
          { name: "未达到预期", slt: false },
          { name: "额外索取费用", slt: false }
        ]
      },
      {
        img: 'face2.png', imgSlt: 'face2_slt.png', text: '满意', style: '#747474', style_slt: '#e8a514', laberList: [
          { name: "态度端正", slt: false },
          { name: "尽心尽责", slt: false },
          { name: "达到预期", slt: false },
          { name: "效率高", slt: false },
        ]
      },
      {
        img: 'face3.png', imgSlt: 'face3_slt.png', text: '超赞', style: '#747474', style_slt: '#ff3a2d', laberList: [
          { name: "态度端正", slt: false },
          { name: "尽心尽责", slt: false },
          { name: "达到预期", slt: false },
          { name: "效率高", slt: false }
        ]
      }
    ],
    faceList: [],
    evalLabelList: [],
    wordDesShow: false,//文字描述
    faceImdex: "2",
    serviceStartDefault: [
      { start: "img/star.png", start_slt: "img/star_slt.png", slt: false, id: 0 },
      { start: "img/star.png", start_slt: "img/star_slt.png", slt: false, id: 1 },
      { start: "img/star.png", start_slt: "img/star_slt.png", slt: false, id: 2 },
      { start: "img/star.png", start_slt: "img/star_slt.png", slt: false, id: 3 },
      { start: "img/star.png", start_slt: "img/star_slt.png", slt: false, id: 4 }
    ],
    serDes: "",//服务描述
    preventStatus: true,
    weatherEval: true,//是否评价过
    serviceAtt: [],
    responseAtt: [],
    specialtyAtt: [],
    serviceAttFlag: "",
    responseAttFlag: "",
    specialtyAttFlag: "",
    currentNum: 0,
    newFileList: new Array(),
    ifLJPJ: false,
    isShareManage: false,
    shareList:new Array(),
    caseId:'',
    showModel:false,
    showHomeBtn:false,
    animationM: {},
    animationS: {},
    isAlredyLoad: false,//打开文档返回后页面不要刷新
  },

  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    if (options.caseId) {
      this.setData({
        caseId: options.caseId,
        showHomeBtn: true
      });
    }
  },

  //点击返回首页
  goHome: function () {
    wx.redirectTo({
      url: '../index/index',
    })
  },

  goDetail:function(){
    this.setData({ isAlredyLoad:true})
    wx.navigateTo({
      url: '../caseDetail/caseDetail',
    })
  },
  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function (ops) {
  //判断案件进入的场景（列表进入、推送消息进入）
    if (this.data.isAlredyLoad) {
      this.setData({ isAlredyLoad: false })
      return
    }
    if (app.globalData.userInfo && !this.data.caseId){//列表进入
      this.getCaseInfoByCaseId('cacheid');
    }else{//消息推送
      let _that = this;
      if (!app.globalData.userInfo){//判断是否登录过
        app.getAuthUserInfo((res) => {//未登录
          // 可以将 res 发送给后台解码出 unionId
          res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
          app.globalData.userInfo = res.userInfo;
          app.globalData.encryptedData = res.encryptedData;
          app.globalData.iv = res.iv;
          wx.showLoading({
            title: '加载中',
          })
          _that.getOpenid(_that);
        }, (res) => {
          console.log("获取用户信息失败=", res)
          _that.setData({
            showModel: true
          })
        });
      }else{//已登录
        this.getCaseInfoByCaseId('nocacheid');
      }
    }
  },

  //获取openid
  getOpenid: (_that) => {
    request.request_api(app.globalData.code, (data) => {
      console.log("openid成功", data)
      app.globalData.openid = data.data.openid;
      app.globalData.session_key = data.data.session_key;
      try {
        if (data.data.unionid) {
          app.globalData.unionid = data.data.unionid
        } else {
          //开始解析获取Unionid
          let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
          let decodeData = pc.decryptData(app.globalData.encryptedData, app.globalData.iv);
          console.log('解密后 decodeData: ', decodeData);
          app.globalData.unionid = decodeData.unionid
        }
      } catch (e) {
        console.log("抛出异常=", e)
        wx.hideLoading()
        //开始解析获取Unionid
        let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
        let decodeData = pc.decryptData(app.globalData.encryptedData, app.globalData.iv);
        console.log('解密后 decodeData: ', decodeData);
        app.globalData.unionid = decodeData.unionid
      }
       _that.loginApi();
    }, (data) => {
      wx.hideLoading();
      console.log("openid失败", data)
      wx.showModal({
        title: "加载失败",
        content: '请尝重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //登录调用
  loginApi: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl,
      regChannel: '6'
    }
    let _this = this;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (obj) => {
      wx.hideLoading();
      if (obj.data.isSuccess == "F" && obj.data.errorCode == "ERROR_NOT_REG") {
        _this.getLoginInfo(_this);
      } else if (obj.data.isSuccess == "T") {
        console.log("用户登录成功=", obj)
        app.globalData.sessionId = obj.data.sessionId;
        //保存手机号
        app.globalData.mobileNo = JSON.parse(obj.data.body).mobileNo;
        app.globalData.userName = JSON.parse(obj.data.body).userName;
        _this.getCaseInfoByCaseId('nocacheid');
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("用户登录失败=", obj)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })
  },

  // 获取登录信息
  getLoginInfo: (that) => {
    //获取第三方接口登录数据
    let bodyInfo = {
      openid: app.globalData.openid,
      mobileNo: app.globalData.mobileNo,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatarUrl: app.globalData.userInfo.avatarUrl
    };
    let _this = that;
    console.log("bodyInfo====", bodyInfo)
    request.get_api("login", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("获取用户信息成功=", res)
      let bodyData = JSON.parse(res.data.body);
      if (res.data.isSuccess == 'T' && bodyData.memUserInfo.mobileNo) {
        //保存数据
        app.globalData.persionalInfo = bodyData.memUserInfo;
        app.globalData.mobileNo = bodyData.memUserInfo.mobileNo;
        wx.hideShareMenu();
        _this.regErp(_this);
      } else {
        wx.navigateTo({
          url: '../reg/reg',
        })
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取用户信息失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  // 用户注册
  regErp: function (that) {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      mobileNo: app.globalData.mobileNo,
      nickName: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl,
      regChannel: '6',
      mobileCheckNo: "SUCCESS"
    }
    let _that = that;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (res) => {
      wx.hideLoading();
      console.log("注册成功=", res)
      app.globalData.sessionId = res.data.sessionId;
      app.globalData.userName = JSON.parse(res.data.body).userName;
      _that.getCaseInfoByCaseId('nocacheid');
    }, (res) => {
      console.log("注册失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    let res = e.detail;
    that.getOpenid(that);
  },

  //查询某个案件的详情
  getCaseInfoByCaseId:function(flag){
    let caseId = "";
    if(flag == 'nocacheid'){
      caseId = this.data.caseId;
    }else if(flag == 'cacheid'){
      this.setData({
        caseInfoData: app.globalData.caseTempData
      });
      caseId = app.globalData.caseTempData.caseId;
    }
    
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: caseId
    }
    let _this = this;
    request.requestLogin_api("queryCaseInfoDetail", headerInfo, bodyInfo, (obj) => {
      console.log("案件详情=", obj)
      let caseInfo = JSON.parse(obj.data.body);
      app.globalData.caseTempData = caseInfo;
      console.log("caseTempData==", caseInfo)
      if (caseInfo.isShareManage == 'Y') {
        _this.setData({
          isShareManage: true,
          shareList: caseInfo.shareList
        });
      }
      // if (flag == 'nocacheid'){
      //   //存储缓存数据
      //   caseInfo.caseAmt = util.filterFormatAmt(caseInfo.caseAmt * 1 / 10000);
      //   caseInfo.status = util.investStatusFilter(caseInfo.status);
      //   _this.setData({
      //     caseInfoData: caseInfo
      //   });
      //   //赋值
      // }

      _this.queryCaseTrackAndDoc();
    }, (obj) => {
      console.log("查询某个案件的详情失败=", obj)
    })
  },

  //swiper滑动
  changeCurrent: function (e) {
    if (e.detail.source == "touch") {
      this.setData({
        currentNum: e.detail.current
      })
    }
  },

  //点击案件进展
  tab1: function () {
    this.setData({
      currentNum: 0
    })
  },

  //点击附件列表
  tab2: function () {
    this.setData({
      currentNum: 1,
    })
  },

  //点击笑脸
  toggleFace: function (e) {
    if (!this.data.weatherEval) {
      return;
    }
    let defaultList = this.data.faceListDefault;
    this.setData({
      faceList: defaultList
    })
    let array = this.data.faceList;
    let index = e.currentTarget.dataset.index;

    if (array[index].img.indexOf('_slt') == -1) {
      array[index].img = 'face' + (index + 1) + '_slt.png'
      array[index].style = array[index].style_slt
    } else {
      array[index].img = 'face' + (index + 1) + '.png'
      array[index].style = '#747474'
    }
    let preventStatus = true;
    if (this.data.serviceAttFlag && this.data.responseAttFlag && this.data.specialtyAttFlag) {
      preventStatus = false;
    }
    this.setData({
      faceList: array,
      faceImdex: index + 1,
      preventStatus: preventStatus,
      evalLabelList: defaultList[index].laberList
    })
  },

  //选中标签
  selectLabel: function (e) {
    if (!this.data.weatherEval) {
      return;
    }
    let index = e.currentTarget.dataset.index;
    console.log("index=", index)
    let arr = this.data.evalLabelList;
    let faceImdex = this.data.faceImdex;
    let faceListDefault = this.data.faceListDefault;

    if (arr[index].slt) {
      arr[index].slt = false;
    } else {
      arr[index].slt = true;
    }
    faceListDefault[faceImdex - 1].laberList = arr;
    this.setData({
      evalLabelList: arr,
      faceListDefault: faceListDefault
    });
  },

  //点击服务态度
  serviceAttFun: function (e) {
    if (!this.data.weatherEval) {
      return;
    }
    let index = e.currentTarget.dataset.index;
    let flag = e.currentTarget.dataset.flag;
    let arr = this.data.serviceStartDefault;
    arr.forEach(function (e) {
      e.slt = false;
    });
    for (let i = 0; i < index + 1; i++) {
      arr[i].slt = true;
    }
    if (flag == '1') {
      this.setData({
        serviceAtt: arr,
        serviceAttFlag: index + 1
      })
    } else if (flag == '2') {
      this.setData({
        responseAtt: arr,
        responseAttFlag: index + 1
      })
    } else if (flag == '3') {
      this.setData({
        specialtyAtt: arr,
        specialtyAttFlag: index + 1
      })
    }

    let preventStatus = true;
    if (this.data.faceImdex && this.data.serviceAttFlag && this.data.responseAttFlag && this.data.specialtyAttFlag) {
      preventStatus = false;
    }
    this.setData({
      preventStatus: preventStatus
    });
  },

  //点击文字描述
  wordDes: function () {
    if (!this.data.weatherEval) {
      return;
    }
    let wordDesShow = this.data.wordDesShow;
    if (!wordDesShow) {
      this.setData({
        wordDesShow: true
      });
    }
  },

  //获取文字描述
  getSerDes: function (e) {
    var des = e.detail.value;
    this.setData({
      serDes: des
    })
  },


  // 显示 评价 弹框
  showToast: function () {
    let tempData = this.data.caseInfoData;
    if (tempData.status == "查看评价" || tempData.status == "立即评价") {
      this.setData({
        isToastBg: true
      })
      let _this = this;
      setTimeout(function () {
        _this.setData({
          isToast: true
        });
      }, 300);
    }
  },
  goAddMember: function() {
    app.globalData.shareList = this.data.shareList;
    // console.log(this.data.shareList.length)
    // if (this.data.shareList.length==0) {
    //   return
    // }
    wx.navigateTo({
      url: '../addMember/addMember',
    })
  },

  //开始查询评价
  startQueryEval: function () {
    wx.showLoading({
      title: '加载中',
    })
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId,
    }
    let bodyInfo = {
      caseId: app.globalData.caseTempData.caseId
    }
    let _that = this;
    request.requestLogin_api("queryUserServiceJudge", headerInfo, bodyInfo, (data) => {
      console.log("查询用户服务评价成功", data)
      let userJudgeData = JSON.parse(data.data.body);
      //判断有没有评价过
      if (userJudgeData.judgeResult && userJudgeData.attitude && userJudgeData.response && userJudgeData.profession) {
        _that.setData({
          weatherEval: false,
          wordDesShow: true
        });
      }
      //赋值每个状态
      let serviceAttStr = JSON.stringify(_that.data.serviceStartDefault);
      let serviceAtt = JSON.parse(serviceAttStr);
      let responseAttStr = JSON.stringify(_that.data.serviceStartDefault);
      let responseAtt = JSON.parse(responseAttStr);
      let specialtyAttStr = JSON.stringify(_that.data.serviceStartDefault);
      let specialtyAtt = JSON.parse(specialtyAttStr);
      if (userJudgeData.attitude > 0) {

        for (let i = 0; i < userJudgeData.attitude; i++) {
          serviceAtt[i].slt = true;
        }
      }
      if (userJudgeData.response > 0) {

        for (let i = 0; i < userJudgeData.response; i++) {
          responseAtt[i].slt = true;
        }
      }
      if (userJudgeData.profession > 0) {

        for (let i = 0; i < userJudgeData.profession; i++) {
          specialtyAtt[i].slt = true;
        }
      }

      //笑脸
      let faceListStr = JSON.stringify(_that.data.faceListDefault);
      let faceList = JSON.parse(faceListStr);
      if (userJudgeData.judgeResult) {
        faceList[userJudgeData.judgeResult - 1].img = faceList[userJudgeData.judgeResult - 1].imgSlt;
        faceList[userJudgeData.judgeResult - 1].style = faceList[userJudgeData.judgeResult - 1].style_slt;
      } else {
        faceList[1].img = faceList[1].imgSlt;
        faceList[1].style = faceList[1].style_slt;
      }

      //文字描述
      let judgeDesc = userJudgeData.judgeDesc;

      //标签
      let evalLabelList = new Array();
      let templist = _that.data.faceListDefault;
      if (!userJudgeData.judgeResult) {
        evalLabelList = templist[1].laberList;
      } else {
        let labelArr = userJudgeData.judgeTags.split(",");
        evalLabelList = templist[userJudgeData.judgeResult - 1].laberList;
        for (let i = 0; i < labelArr.length; i++) {
          for (let j = 0; j < evalLabelList.length; j++) {
            if (labelArr[i] == evalLabelList[j].name) {
              evalLabelList[j].slt = true;
            }
          }
        }
      }

      // caseInfoData: app.globalData.caseTempData
      let tempData = app.globalData.caseTempData;
      if (_that.data.isShareManage){
        if (!_that.data.weatherEval) {
          //tempData.status = "查看评价"
          _that.setData({
            ifLJPJ: true
          })
        } else {
          if (tempData.status == "合同已签约") {
            //tempData.status = "立即评价"
            _that.setData({
              ifLJPJ: true
            })
          }
        }
      }
      _that.setData({
        serviceAtt: serviceAtt,
        responseAtt: responseAtt,
        specialtyAtt: specialtyAtt,
        faceList: faceList,
        serDes: judgeDesc,
        evalLabelList: evalLabelList,
        caseInfoData: tempData
      });
      wx.hideLoading()
      _that.getFileList();
    }, (data) => {
      wx.hideLoading()
      console.log("查询用户服务评价失败", data)
      wx.showModal({
        title: "加载失败",
        content: '请重新尝试',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //点击开始提交评价
  subEval: function () {
    wx.showLoading({
      title: '加载中',
    })
    let arr = this.data.evalLabelList;
    let judgeTags = "";
    arr.forEach(function (e) {
      if (e.slt) {
        judgeTags = judgeTags + e.name + ","
      }
    });
    judgeTags = judgeTags.substring(0, judgeTags.length - 1)

    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId,
    }
    let bodyInfo = {
      caseId: app.globalData.caseTempData.caseId,
      attitude: this.data.serviceAttFlag,
      response: this.data.responseAttFlag,
      profession: this.data.specialtyAttFlag,
      judgeResult: this.data.faceImdex,
      judgeTags: judgeTags,
      judgeDesc: this.data.serDes
    }

    console.log("bodyInfo====", bodyInfo)
    let _that = this;
    request.requestLogin_api("userServiceJudge", headerInfo, bodyInfo, (data) => {
      console.log("提交用户服务评价成功", data)
      if (data.data.isSuccess == 'T') {
        // caseInfoData: app.globalData.caseTempData
        let tempData = app.globalData.caseTempData;
        tempData.status = "查看评价";

        this.setData({
          isToast: false,
          caseInfoData: tempData,
          weatherEval: false,
          wordDesShow: true
        })
        wx.showToast({
          title: '评价成功',
          icon: 'success',
          duration: 2000
        })
        let _this = this;
        setTimeout(function () {
          _this.setData({
            isToastBg: false
          });
        }, 300);
      } else {
        wx.showModal({
          title: "提交评价失败",
          content: '请重新尝试',
          confirmText: '确定',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            } else if (res.cancel) {
            }
          }
        })
      }
      wx.hideLoading()
    }, (data) => {
      wx.hideLoading()
      console.log("提交用户服务评价失败", data)
      wx.showModal({
        title: "加载失败",
        content: '请重新尝试',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  // 隐藏 评价 弹框
  delToast: function () {
    this.setData({
      isToast: false
    })
    let _this = this;
    setTimeout(function () {
      _this.setData({
        isToastBg: false
      });
    }, 300);
  },


  // 展开合并 文件列表
  toggle: function (e) {
    let index = e.currentTarget.dataset.index;
    let fileLength = e.currentTarget.dataset.filelength
    let enforceStepList = this.data.newFileList;
    if (fileLength > 0) {
      if (enforceStepList[index].openFile) {
        enforceStepList.forEach(function (e) {
          e.openFile = false;
        });
      } else {
        enforceStepList.forEach(function (e) {
          e.openFile = false;
        });
        enforceStepList[index].openFile = true;
      }
      this.setData({
        newFileList: enforceStepList
      });
    }
  },


  //点击下载文件
  dowmloadFile: function (e) {
    let _this=this;
    let fileurl = e.currentTarget.dataset.url;
    let docName = e.currentTarget.dataset.name;
    let tempSuf = docName.split('.');
    let suffix = tempSuf[tempSuf.length - 1];
    let fileType = "doc,xls,ppt,pdf,docx,xlsx,pptx";
    let picSuffix = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,jpeg";
    console.log("fileurl==", fileurl)
    wx.downloadFile({
      url: fileurl, //仅为示例，并非真实的资源
      success: function (res) {
        _this.setData({ isAlredyLoad: true })
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log("读取文件成功=", res)
        // if (res.statusCode === 200) {
        var filePath = res.tempFilePath
        if (fileType.indexOf(suffix) != "-1") {
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        } else if (picSuffix.indexOf(suffix.toLowerCase()) != "-1") {
          wx.previewImage({
            current: filePath, // 当前显示图片的http链接
            urls: [filePath] // 需要预览的图片http链接列表
          })
        }
      },
      fail: function (res) {
        console.log("读取文件失败=", res);
      }
    })
  },

 

  //获取文件列表
  getFileList: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: app.globalData.caseTempData.caseId
    }
    let _this = this;
    request.requestLogin_api("queryDocList4MP", headerInfo, bodyInfo, (obj) => {
      console.log("查询文件列表成功==", obj)
      let tempData = JSON.parse(obj.data.body);
      //开始处理数据
      let enforceTempList = tempData.lawsuitEnforceVo.enforceStepRecordWithBLOBs; //执行文本
      if (enforceTempList) {
        if (enforceTempList.length > 0) {
          enforceTempList.forEach(function (e, index) {
            let monthDate = util.timetrans(e.finishTime, "day");
            e.monthDate = monthDate.substring(5, 10)
            e.dayHM = util.timetrans(e.finishTime, "timeHM");
            e.openFile = false;
            if (index == 0) {
              e.stepFlag = true;
            } else {
              e.stepFlag = false;
            }
            if (e.enforceStepRecordDocs.length > 0) {
              let tempList = e.enforceStepRecordDocs;
              tempList.forEach(function (item) {
                let tempUrl = item.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
                item.docName = tempUrl.substring(10, tempUrl.length);
              });
              e.enforceStepRecordDocs = tempList;
            }
          });
        }
      } else {
        enforceTempList = new Array();
      }

      let lawsuitTempList = tempData.lawsuitEnforceVo.lawsuitStepRecordWithBLOBs; //诉讼文本
      if (lawsuitTempList) {
        if (lawsuitTempList.length > 0) {
          lawsuitTempList.forEach(function (e, index) {
            let monthDate = util.timetrans(e.finishTime, "day");
            e.monthDate = monthDate.substring(5, 10)
            e.dayHM = util.timetrans(e.finishTime, "timeHM");
            e.openFile = false;
            if (index == 0) {
              e.stepFlag = true;
            } else {
              e.stepFlag = false;
            }

            if (e.lawsuitStepRecordDocs.length > 0) {
              let tempList = e.lawsuitStepRecordDocs;
              tempList.forEach(function (item) {
                let tempUrl = item.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
                item.docName = tempUrl.substring(10, tempUrl.length);
              });
              e.lawsuitStepRecordDocs = tempList;
              e.enforceStepRecordDocs = tempList;
            } else {
              e.enforceStepRecordDocs = new Array();
            }
          });
        }
      } else {
        lawsuitTempList = new Array();
      }

      let docCaseDocs = tempData.docCaseDocs;//合同文本
      // console.log("合同文本=", docCaseDocs)
      let docTempCaseDocs = new Array();
      if (docCaseDocs.length > 0) {
        docCaseDocs.forEach(function (e, index) {
          e.monthDate = e.uploadDate.substring(4, 6) + "-" + e.uploadDate.substring(6, 8);
          e.dayHM = e.uploadTime.substring(0, 2) + "-" + e.uploadTime.substring(2, 4);
          e.openFile = false;
          let tempUrl = e.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
          e.docName = tempUrl.substring(10, tempUrl.length);
        });
        docTempCaseDocs = [{
          monthDate: docCaseDocs[0].monthDate,
          dayHM: docCaseDocs[0].dayHM,
          openFile: docCaseDocs[0].openFile,
          recordText: "合同文本",
          stepFlag: true,
          enforceStepRecordDocs: docCaseDocs
        }]
      }
      // console.log("合同文本=", docTempCaseDocs)

      let applyDocs = tempData.applyDocs;//申请资料
      let docTempApplyDocs = new Array();
      if (applyDocs.length > 0) {
        applyDocs.forEach(function (e) {
          e.monthDate = e.uploadDate.substring(4, 6) + "-" + e.uploadDate.substring(6, 8);
          e.dayHM = e.uploadTime.substring(0, 2) + "-" + e.uploadTime.substring(2, 4);
          e.openFile = false;
          let tempUrl = e.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
          e.docName = tempUrl.substring(10, tempUrl.length);
        });
        docTempApplyDocs = [{
          monthDate: applyDocs[0].monthDate,
          dayHM: applyDocs[0].dayHM,
          openFile: applyDocs[0].openFile,
          recordText: "申请资料",
          stepFlag: true,
          enforceStepRecordDocs: applyDocs
        }]
      }

      //合并数组
      let newArr = enforceTempList.concat(lawsuitTempList, docTempCaseDocs, docTempApplyDocs);
      _this.setData({
        newFileList: newArr
      });
    }, (obj) => {
      console.log("查询文件列表失败==", obj)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
  },

  queryCaseTrackAndDoc: function(){
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: app.globalData.caseTempData.caseId
    }
    let _this = this;
    request.requestLogin_api("queryCaseTrackAndDoc", headerInfo, bodyInfo, (obj) => {
      var res = JSON.parse(obj.data.body), _trackRecords = [], _showMoreBtn = false;
      console.log('queryCaseTrackAndDoc_res', res)
      var arr = res.enforceTrackRecords.concat(res.lawsuitTrackRecords).concat(res.riskTrackRecords);
      console.log('queryCaseTrackAndDoc',arr)
      arr.forEach(function (e) {
        e.dateStr = e.trackRecordBean.operDate.substring(5);
        e.clock = e.trackRecordBean.operTime.substring(0, 5);
        if (e.caseDocBeans.length > 0) {
          e.openFile = true;
        }else{
          e.openFile = false;
        }
        e.caseDocBeans.forEach((item) => {
          item.docUrlStr = item.docUrl.replace(app.globalData.winhc_oss_url, '').replace(app.globalData.old_winhc_oss_url, '').replace(/[A-Z|A-z|2-8]{10}/, '');
        })
      });
      if (arr.length > 3) {
        _trackRecords = arr.slice(0, 3);
        _showMoreBtn = true;
      } else {
        _trackRecords = arr;
        _showMoreBtn = false;
      }
      _this.setData({
        trackRecords: _trackRecords,
        trackRecordsAll: arr,
        showMoreBtn: _showMoreBtn
      });
      _this.startQueryEval();
    }, (obj) => {
      console.log("查询某个案件的站内信列表失败==", obj)
    })
  },
  showMore : function () {
    let trackRecordsAll = this.data.trackRecordsAll
    if (trackRecordsAll.length > 3) {
      if (this.data.showMoreTrick) {
        this.setData({
          trackRecords: trackRecordsAll.slice(0, 3),
          showMoreTrick: false
        })
      } else {
        this.setData({
          trackRecords: trackRecordsAll,
          showMoreTrick: true
        })
      }
    }
  },
  showFile:function(e){
    let showfileindex = e.currentTarget.dataset.showfileindex;
    let _trackRecords = this.data.trackRecords
    if (_trackRecords[showfileindex].caseDocBeans.length > 0) {
      _trackRecords[showfileindex].openFile = !_trackRecords[showfileindex].openFile;
      this.setData({ trackRecords:_trackRecords})
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  userLevel:function(){
    this.setData({ isToastBg: true })
    let _this = this;
    setTimeout(function () {
      _this.setData({
        isToast: true
      });
    }, 300);
  },
  //转发
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log("来自页面内的转发", res.target)
    }
    let This = this;
    let userName = app.globalData.userName ? app.globalData.userName : app.globalData.userInfo.nickName
    return {
      title: userName + "邀请你关注本案件最新进展",
      path: 'pages/caseShareDescribe/caseShareDescribe?caseId=' + app.globalData.caseTempData.caseId + "|" + userName,
      // imageUrl: '../../img/logo2.png',
      success: function (res) {
        // 转发成功
        console.log("转发成功返回数据=", res)
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });

        if (res.shareTickets) {
          // 获取转发详细信息
          wx.getShareInfo({
            shareTicket: res.shareTickets[0],
            success(res) {
              // res.errMsg; // 错误信息
              // res.encryptedData;  //  解密后为一个 JSON 结构（openGId    群对当前小程序的唯一 ID）
              // res.iv; // 加密算法的初始向量
              // let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
              // let decodeData = pc.decryptData(res.encryptedData, res.iv);
              // console.log('解密后 decodeData: ', decodeData);
              // This.setData({
              //   opengidName: decodeData.openGId
              // });
            },
            fail() { },
            complete() { }
          });
        }
      },
      fail: function (res) {
        // 转发失败
      },
      complete: function () {

      }
    }
  },
})
